package io.kiki.sba.registry.common.model.slot.func;

import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import io.kiki.sba.registry.common.model.slot.SlotConfig;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;


public class Crc32cSlotFunction implements SlotFunction {
    public static final Crc32cSlotFunction INSTANCE = new Crc32cSlotFunction();
    private static final Charset UTF8 = StandardCharsets.UTF_8;
    private final int slotMask;
    private final HashFunction hashFunction = Hashing.crc32c();

    public Crc32cSlotFunction() {
        this(SlotConfig.SLOT_NUM);
    }

    public Crc32cSlotFunction(int slotNums) {
        this.slotMask = slotNums - 1;
    }

    @Override
    public String name() {
        return "crc32c";
    }

    @Override
    public int maxSlots() {
        return slotMask + 1;
    }

    @Override
    public int slotOf(Object o) {
        return getCrc32Code(o) & slotMask;
    }

    private int getCrc32Code(Object o) {
        byte[] bytes = o.toString().getBytes(UTF8);
        return Math.abs(hashFunction.hashBytes(bytes).asInt());
    }
}
